package org.liuqm.common;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class RequestMappingAnalysis {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

//        System.out.println(RequestMapping.class.getResource("/").getPath());
        System.out.println( getRequestMapping("org.liuqm.controller"));
    }


    public static Map getRequestMapping(String packageName) throws IOException, ClassNotFoundException {
        String basePath = RequestMapping.class.getResource("/").getPath()+"\\";
        String packStr=packageName.replace(".","\\");
//        System.out.println("packStr:"+packStr);
        File file = new File(basePath+packStr);


        Map<String,String> urlMap = new HashMap<String,String>();

        if (file.isDirectory()) {//当前路径为文件夹
            File[] files = file.listFiles();//取出当前文件夹下的所有文件
            for (File file1 : files) {
                if (file1.isFile()) {//判断是否为文件
                    String className=packageName+"."+file1.getName();
                    className=className.substring(0,className.lastIndexOf("."));

                    Class clazz = Class.forName(className);
                    String baseUrl="";
                    if(clazz.getAnnotation(RequestMapping.class)!=null){
                        RequestMapping typeAnno= (RequestMapping) clazz.getAnnotation(RequestMapping.class);
                        baseUrl=typeAnno.value();
                    }

                    Method[] methods=clazz.getMethods();
                    for (Method method : methods) {
                        if(method.getAnnotation(RequestMapping.class)!=null) {
                            RequestMapping typeAnno = (RequestMapping) method.getAnnotation(RequestMapping.class);
                            String methodUrl=typeAnno.value();
                            urlMap.put(baseUrl+methodUrl,className+"."+method.getName());
                        }
                    }
                }

            }

        }
        return urlMap;
    }
}
